<template>
  <div>
    <h1>Login</h1>
    <form @submit.prevent="login">
      <input v-model="username" type="username" placeholder="username" />
      <input v-model="email" type="email" placeholder="Email" />
      <input
        v-model="password"
        type="password"
        placeholder="Password"
        required
      />
      <button type="submit">Login</button>
    </form>
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { auth } from "../lib/auth-client";
import { useRouter } from "vue-router";

const username = ref("");
const email = ref("");
const password = ref("");
const error = ref<string | null>(null);
const router = useRouter();

const login = async () => {
  error.value = null;
  try {
    let result = null;
    if (username.value) {
      result = await auth.signIn.username({
        username: username.value,
        password: password.value,
      });
    } else {
      result = await auth.signIn.email({
        email: email.value,
        password: password.value,
      });
    }

    if (result.error) {
      throw new Error(result.error.message);
    }

    router.push("/profile");
  } catch (err) {
    error.value = (err as Error).message;
  }
};
</script>
